// import type { User } from '@/types/user'
import { defineStore } from 'pinia'
import { ref, shallowRef } from 'vue'
import { pinyin } from 'pinyin-pro'
import routerIndex from '@/router/index'
import { routes } from '@/router/index'
import GeRenJiFenDetails from '@/views/customizedPage/GeRenJiFen/GeRenJiFenDetails.vue'
import HuaXiangDetails from '@/views/customizedPage/ZhuangWeiRenYuanHuaXiang/HuaXiangDetails.vue'
/**
 * @Author: 段晓龙
 * @Date: 2024-09-18 17:0:19
 * @Description: 用户信息存储 包括动态路由导航的存储
 * @LastEditors: 段晓龙
 */
export const useUserStore = defineStore(
  'cnac-user',
  () => {
    // 自定义页面路由
    const pathsArry = ref<any>([])
    // 自定义多维页面路由
    const setPathsArry = (info: any) => {
      pathsArry.value = info
    }
    // 需要缓存的路由
    const cacheArry = ref<any>([])
    const clearCacheArry = () => (cacheArry.value = [])
    // 用户token
    const token = ref<string>('')
    const setToken = (t: string) => (token.value = t)
    const clearToken = () => (token.value = '')
    // 用户导航
    const userNav = shallowRef<any>()
    const setUserNav = (info: any) => (userNav.value = info)
    const clearUserNav = () => (userNav.value = undefined)
    // 用户导航信息
    const navInfo = ref<any>()
    const setNavInfo = (info: any) => (navInfo.value = info)
    const clearNavInfo = () => (navInfo.value = undefined)
    // 用户应用信息
    const appInfo = ref<any>()
    const setAppInfo = (info: any) => (appInfo.value = info)
    const clearAppInfo = () => (appInfo.value = undefined)
    // 用户信息
    const user = ref<any>()
    const setUser = (u: any) => (user.value = u)
    const clearUser = () => (user.value = undefined)
    const returnUrl = ref('')
    const setReturnUrl = (url: string) => (returnUrl.value = url)

    const PinYinStr = (str: string) => {
      if (!str) return ''
      const NameInfo = pinyin(str, { toneType: 'none' })
        ?.split(' ')
        .map((item) => item.charAt(0).toUpperCase() + item.substring(1))
        .join('')

      return NameInfo
    }
    const PinYinStrSmall = (str: string) => {
      const stringWithoutSymbols = str.match(/[\u4e00-\u9fa5]/g)?.join('') // 去除所有非中文字符
      const NameInfo = pinyin(stringWithoutSymbols as string, { toneType: 'none' })
        ?.split(' ')
        .map((item) => item.charAt(0).toUpperCase() + item.substring(1))
        .join('')

      return NameInfo
    }

    const creatNavBar = () => {
      cacheArry.value = []
      const navInfos = Function('return ' + navInfo.value)()
      const appInfos = Function('return ' + appInfo.value)()
      // console.log('navInfos', navInfos)
      // console.log('appInfos', appInfos)
      const routesArry = shallowRef<any>()
      const getRoutesArry = () => {
        // 一级路由框架
        routesArry.value = navInfos.map((item: any) => {
          // 这里的嵌套结构主要是 "系统管理" 的结构，其他路由基本不会在这里出现
          return {
            path: `/${PinYinStr(item.text)}`,
            name: PinYinStr(item.text),
            meta: {
              attributes: item.attributes, // 携带信息 远古信息未做任何处理
              title: item.text,
              keepAlive: false,
              hidden: false
            },
            redirect: item.text === '系统管理' ? '/XiTongGuanLi/XiTongGuanLi/JueSeGuanLi' : '',
            component: () => import('@/layout/fourthNavLayout.vue'),
            children: item.children
              ? item.children.map((twoItem: any) => {
                  return {
                    path: `/${PinYinStr(item.text)}/${PinYinStr(twoItem.text)}`,
                    name: PinYinStr(twoItem.text),
                    meta: {
                      attributes: twoItem.attributes, // 携带信息 远古信息未做任何处理
                      title: twoItem.text,
                      keepAlive: false,
                      hidden: false
                    },
                    children: twoItem.children
                      ? twoItem.children.map((threeItem: any) => {
                          cacheArry.value.push(
                            `/${PinYinStr(item.text)}/${PinYinStr(twoItem.text)}/${PinYinStr(threeItem.text)}`
                          )
                          return {
                            path: `/${PinYinStr(item.text)}/${PinYinStr(twoItem.text)}/${PinYinStr(threeItem.text)}`,
                            name: `/${PinYinStr(item.text)}/${PinYinStr(twoItem.text)}/${PinYinStr(threeItem.text)}`,
                            meta: {
                              attributes: threeItem.attributes, // 携带信息 远古信息未做任何处理
                              title: threeItem.text,
                              keepAlive: true,
                              hidden: false,
                              isMulti: false,
                              iframeComponent: threeItem.text === 'SQL报表管理' ? true : false
                            },
                            component: () =>
                              import(`@/views/system/${PinYinStr(threeItem.text)}/index.vue`)
                          }
                        })
                      : []
                  }
                })
              : []
          }
        })
        routesArry.value = routesArry.value.filter((item: any) => item.meta.title !== '首页')
        // 系统管理 放到在最后面
        const systemManage = routesArry.value.find((item: any) => item.meta.title === '系统管理')
        // console.log(systemManage)
        if (systemManage) {
          routesArry.value = routesArry.value.filter((item: any) => item.meta.title !== '系统管理')
          routesArry.value.push(systemManage)
        }

        // 是否是iframe
        const isIframe = (urlInfo: string, attributes: any) => {
          const isInfo = pathsArry.value.includes(`/${urlInfo}`)
          const isMultiDimensional =
            attributes.new_url.split('?')[0] === '/multiDimensional' ? true : false
          if (isInfo) {
            return false
          } else if (isMultiDimensional) {
            return false
          } else {
            return true
          }
        }
        //
        const getSubComponents = (urlInfo: string, attributes?: any) => {
          const isInfo = pathsArry.value.includes(`/${urlInfo}`)
          const isMultiDimensional =
            attributes.new_url.split('?')[0] === '/multiDimensional' ? true : false
          // console.log('isInfo', urlInfo, 'isMultiDimensional', isMultiDimensional)

          if (isInfo) {
            return () => import(`@/views/customizedPage/${urlInfo}/index.vue`)
          } else if (isMultiDimensional) {
            return () => import('@/views/multiDimensional/index.vue')
          } else {
            return () => import('@/components/tableBox/index.vue')
          }
        }

        // 子路由
        const childrenRoutesArry = appInfos.map((item: any) => {
          return {
            path: `/${PinYinStr(item.text)}`,
            name: PinYinStr(item.text),
            // attributes: item.attributes, // 携带信息 远古信息未做任何处理
            meta: {
              attributes: item.attributes,
              title: item.text,
              keepAlive: false,
              hidden: false
            },
            children: item.children
              ? item.children.map((twoItem: any) => {
                  return {
                    path: `/${PinYinStr(item.text)}/${PinYinStr(twoItem.text)}`,
                    name: PinYinStr(twoItem.text),
                    // attributes: twoItem.attributes, // 携带信息 远古信息未做任何处理
                    meta: {
                      attributes: twoItem.attributes,
                      title: twoItem.text,
                      keepAlive: false,
                      hidden: false
                    },
                    children: twoItem.children
                      ? twoItem.children.map((threeItem: any) => {
                          /**
                           * 2024.09.23 项目上线生产环境出现导航渲染问题
                           * 问题：线上有人将四级导航放的表放在三级，导致导航渲染失败
                           * 解决：新增 if (threeItem.attributes.tp === 1) 判断
                           */
                          if (threeItem.attributes.tp === 1) {
                            return {
                              path: `/${PinYinStr(item.text)}/${PinYinStr(twoItem.text)}/${PinYinStr(threeItem.text)}`,
                              name: `${PinYinStr(twoItem.text)}${PinYinStr(threeItem.text)}`,
                              meta: {
                                attributes: threeItem.attributes,
                                title: threeItem.text,
                                keepAlive: true,
                                hidden: false
                              },
                              children: [
                                {
                                  path: `/${PinYinStr(item.text)}/${PinYinStr(twoItem.text)}/${PinYinStr(threeItem.text)}/${PinYinStr(threeItem.text)}s`,
                                  name: `item${threeItem.id.split(',')[0]}${threeItem.id.split(',')[1]}`,
                                  meta: {
                                    attributes: threeItem.attributes,
                                    title: threeItem.text,
                                    keepAlive: true,
                                    hidden: false,
                                    isMulti:
                                      threeItem.attributes.new_url.includes('/multiDimensional'),
                                    iframeComponent: !pathsArry.value.includes(
                                      `/${PinYinStrSmall(threeItem.text)}`
                                    )
                                  },
                                  component: pathsArry.value.includes(
                                    `/${PinYinStrSmall(threeItem.text)}s`
                                  )
                                    ? () =>
                                        import(
                                          `@/views/customizedPage/${PinYinStrSmall(threeItem.text)}/index.vue`
                                        )
                                    : () => import('@/components/tableBox/index.vue')
                                }
                              ]
                            }
                          } else {
                            return {
                              path: `/${PinYinStr(item.text)}/${PinYinStr(twoItem.text)}/${PinYinStr(threeItem.text)}`,
                              name: `${PinYinStr(twoItem.text)}${PinYinStr(threeItem.text)}`,
                              // attributes: threeItem.attributes, // 携带信息 远古信息未做任何处理
                              meta: {
                                attributes: threeItem.attributes,
                                title: threeItem.text,
                                keepAlive: true,
                                hidden: false
                              },
                              children: threeItem.children
                                ? threeItem.children.map((fourItem: any) => {
                                    if (
                                      pathsArry.value.includes(`/${PinYinStrSmall(fourItem.text)}`)
                                    ) {
                                      cacheArry.value.push(
                                        `/${PinYinStr(item.text)}/${PinYinStr(twoItem.text)}/${PinYinStr(threeItem.text)}/${PinYinStrSmall(fourItem.text)}`
                                      )
                                    }

                                    return {
                                      path: `/${PinYinStr(item.text)}/${PinYinStr(twoItem.text)}/${PinYinStr(threeItem.text)}/${PinYinStrSmall(fourItem.text)}`,
                                      name: `/${PinYinStr(item.text)}/${PinYinStr(twoItem.text)}/${PinYinStr(threeItem.text)}/${PinYinStrSmall(fourItem.text)}`,
                                      // attributes: fourItem.attributes, // 携带信息 远古信息未做任何处理
                                      meta: {
                                        attributes: fourItem.attributes,
                                        title: fourItem.text,
                                        keepAlive: true,
                                        hidden: false,
                                        isMulti:
                                          fourItem.attributes.new_url.includes('/multiDimensional'),
                                        iframeComponent: isIframe(
                                          PinYinStrSmall(fourItem.text),
                                          fourItem.attributes
                                        )
                                      },
                                      component: getSubComponents(
                                        PinYinStrSmall(fourItem.text),
                                        fourItem.attributes
                                      )
                                    }
                                  })
                                : []
                            }
                          }
                        })
                      : []
                  }
                })
              : []
          }
        })
        // console.log('routesArry', routesArry.value)
        // console.log('childrenRoutesArry', childrenRoutesArry)
        routesArry.value.forEach((routesItem: any) => {
          childrenRoutesArry.forEach((childrenItem: any) => {
            if (routesItem.path === childrenItem.path) {
              routesItem.children = childrenItem.children
            }
          })
        })
        routes[0].children?.concat(...routesArry.value).forEach((routerItem: any) => {
          routerIndex.addRoute('layoutIndex', { ...routerItem })
        })
        routerIndex.addRoute('BianGengCaoZuoGeRenJiFen', {
          path: '/YunWangAnQuan/BianGengCaoZuo/GeRenJiFen/Details',
          name: 'GeRenJiFenDetails',
          meta: {
            title: '个人积分详情',
            keepAlive: true,
            hidden: false,
            isMulti: false,
            iframeComponent: false
          },
          component: GeRenJiFenDetails
        })
        routerIndex.addRoute('ZhuangWeiGongZuoLiangHeSuanGongChengShiHuaXiang', {
          path: '/ZhuangWeiYeWu/ZhuangWeiGongZuoLiangHeSuan/GongChengShiHuaXiang/Details',
          name: 'ZhuangWeiRenYuanHuaXiangDetails',
          meta: {
            title: '画像详情',
            keepAlive: true,
            hidden: false,
            isMulti: false,
            iframeComponent: false
          },
          component: HuaXiangDetails
        })
        cacheArry.value.push(
          '/YunWangAnQuan/BianGengCaoZuo/GeRenJiFen/Details',
          '/ZhuangWeiYeWu/ZhuangWeiGongZuoLiangHeSuan/GongChengShiHuaXiang/Details'
        )
        setUserNav(routes[0].children?.concat(...routesArry.value))
        // console.log('routerIndex', routerIndex)
      }
      getRoutesArry()
    }
    // 退出登录清除用户信息
    const clearUserStore = () => {
      pathsArry.value = []
      clearToken()
      clearUserNav()
      clearNavInfo()
      clearAppInfo()
      clearUser()
      clearCacheArry()
      // clearIframeCacheArry()
    }
    return {
      pathsArry, // 路由路径
      setPathsArry, // 设置路由路径
      cacheArry,
      clearCacheArry,
      token,
      setToken,
      clearToken,
      userNav,
      setUserNav,
      clearUserNav,
      navInfo,
      setNavInfo,
      clearNavInfo,
      appInfo,
      setAppInfo,
      clearAppInfo,
      user,
      setUser,
      clearUser,
      returnUrl,
      setReturnUrl,
      clearUserStore,
      creatNavBar
    }
  },
  {
    persist: true // 开启持久化
  }
)
